package org.example.spring.controller.User;


import io.swagger.annotations.ApiOperation;
import jakarta.validation.constraints.Pattern;
import org.example.spring.domain.pojo.Result;
import org.example.spring.domain.pojo.User;
import org.example.spring.service.UserService;
import org.example.spring.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController("userController")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        //查询用户
        User u = userService.findByUserName(user.getUsername());
        if (u == null) {
            userService.register(user);
            return Result.success();
        } else {
            return Result.error("用户已存在");
        }
        //注册
    }

    //登录
    @PostMapping("/login")
    @ApiOperation(value = "用户登入")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);

        //判断用户是否存在
        if(loginUser!=null){
            String loginPwd = loginUser.getPassword();
            if(loginPwd.equals(password)){
                Map<String,Object>claims=new HashMap<>();
                claims.put("userId",loginUser.getUserId());
                String token= JwtUtil.genToken(claims);
                return Result.success(token);
            }else{
                return Result.error("密码错误");
            }

        }else{
            return Result.error("用户名或密码错误");
        }
    }

    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String phone = params.get("phone");
        String newPwd = params.get("password");
        String rePwd = params.get("rePassword");
        //判断参数是否为空
        if(username == null || phone == null || newPwd == null || rePwd == null) {
            return Result.error("参数不能为空");
        }
        User loginUser = userService.findByUserName(username);
        if(loginUser == null) {
            return Result.error("用户不存在");
        }
        if(!loginUser.getPhone().equals(phone)){
            return Result.error("手机号错误");
        }

        if (!newPwd.equals(rePwd)) {
            return Result.error("两次密码不一致");
        }
        loginUser.setPassword(newPwd);
        userService.updatePwd(loginUser);
        return Result.success();
    }
}
